const fs = require('fs');
const http = require('http');

// 确定读取路径
const filePath = process.argv[2] || __filename;

const server = http.createServer((req, res) => {
    // 创建文件读取流
    const readStream = fs.createReadStream(filePath, 'utf8');

    // 流事件处理
    readStream.on('data', (chunk) => {
        // 接收数据块并写入响应
        res.write(chunk);
    });

    readStream.on('end', () => {
        // 读取完成，结束响应
        res.end();
    });

    readStream.on('error', (err) => {
        // 处理流错误
        res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(`错误：流读取失败 - ${err.message}`);
        console.error('流读取错误：', err.message);
    });

    // 设置响应头（可在data事件前设置）
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
});

server.listen(8081, () => {
    console.log(`服务器已启动，监听端口8081`);
    console.log(`当前读取目标：${filePath}`);
    console.log(`请访问 http://localhost:8081 查看结果`);
});